import axios from 'axios'
export default {
  namespaced: true, // 开启命名空间
  state: {
    list: [] //准备存储购物车
  },
  mutations: {
    updateList (state, val) {
      state.list = val
    },
    // 修改状态的方法
    updateState (state, id) {
      const row = state.list.find(item => item.id === id)
      row.goods_state = !row.goods_state
    },
    updateCount (state, obj) {
      const row = state.list.find(item => item.id === obj.id)
      if (row.goods_count === 1 && obj.var === -1) return
      row.goods_count += obj.var
    },
    updateAllState (state, boo) {
      state.list.forEach(item => (item.goods_state = boo))
    }
  },
  actions: {
    async initData (store) {
      const { data: res } = await axios.get(
        'http://www.itcbc.com:3006/api/cart'
      )
      store.commit('updateList', res.list)
    }
  },
  getters: {
    isFull (state) {
      return state.list.every(item => item.goods_state === true)
    },
    zonghe (state) {
      const aa = state.list.filter(item => item.goods_state === true)
      return aa.reduce(function (prev, item) {
        return prev + item.goods_price * item.goods_count
      }, 0)
    },
    shuliang (state) {
      return state.list
        .filter(item => item.goods_state === true)
        .reduce(function (prev, item) {
          return prev + item.goods_count
        }, 0)
    }
  }
}
